<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/4
 * Time: 15:33
 */
namespace Controller;
use Model\IndexModel;
use Shop\Controller;

if(!defined('SHOP')){
    header("Location:/index.php");
}

class OrderController extends TooController{
    public function __construct()
    {
        parent::__construct();

        if(!$_SESSION['Home']['Member']['id']){
            header("Location:/index.php?C=Login&F=login");
        }
    }

    //购物车列表
    public function flow(){
        $goods=$this->model->pdo_sel("select f.*,g.kc,g.img,g.name,g.money,u.gname,u.gmoney from sh_flow as f join sh_goods as g on f.g_id = g.id join sh_goods_g as u on f.gg_id = u.id where f.m_id = '{$_SESSION['Home']['Member']['id']}' and f.stat =1",2);

        $this->view->assign('goods',$goods);
        $this->view->display();
    }

    //购物车修改和删除
    public function flowUpd(){
        $id=$_GET['id'];
        $type=$_GET['type'];
        if($type=='upd'){
            //修改数量
            $add=$_GET['add'];
            if($add=='jia'){
             $this->model->pdo_exec("update sh_flow set num = num+1 where id = $id");
            }else if($add=='jian'){
                $this->model->pdo_exec("update sh_flow set num = num-1 where id = $id");
            }
        }else{
            //删除数据
            if($this->model->pdo_exec("delete from sh_flow where id = $id limit 1")){
                $this->retuAjax(array('type'=>2,'msg'=>'删除成功'));
            }else{
                $this->retuAjax(array('type'=>2,'msg'=>'删除失败'));
            }
        }
    }

    //立即购买
    public function ljgm(){
        //向购物车表添加数据
        $arr=array();
        $arr['gg_id']=$_GET['gg_id'];
        $arr['g_id']=$_GET['g_id'];
        $arr['num']=$_GET['num'];
        $arr['time']=time();
        $arr['stat']=2;
        $arr['m_id']=$_SESSION['Home']['Member']['id'];
        $id=$this->model->pdo_insert('sh_flow',$arr);
        //插入数据库
        if($id){
            //跳转到结算页面
            $this->redirect("Order","add&id=$id");
        }else{
            $this->success('系统错误',"Index","goods_msg&id=".$_GET['g_id']);
        }

    }


    //结算页面
    public function add(){
        $id=$_GET['id'];
        $id=trim($id,','); //最终的数据 1,3
        $_SESSION['Home']['orderid']=$id;

        //商品数据
        $arr=$this->model->pdo_sel("select f.*,g.kc,g.img,g.name,g.money,u.gname,u.gmoney from sh_flow as f join sh_goods as g on f.g_id = g.id join sh_goods_g as u on f.gg_id = u.id where f.id in ($id)",2);
        $this->view->assign('arr',$arr);

        //地址
        $path=$this->model->pdo_sel("select * from sh_path where m_id = '{$_SESSION['Home']['Member']['id']}'",2);
        $this->view->assign('paths',$path);
        $this->view->display();
    }

    //地址编辑
    public function path(){
        if($_POST){
            $arr=array();
            $arr['m_id']=$_SESSION['Home']['Member']['id'];
            $arr['sheng']=$_POST['sheng'];
            $arr['shi']=$_POST['shi'];
            $arr['qu']=$_POST['qu'];
            $arr['txt']=$_POST['txt'];
            $arr['ycode']=$_POST['ycode'];
            $arr['name']=$_POST['name'];
            $arr['phone']=$_POST['phone'];
            $this->model->pdo_insert("sh_path",$arr);

            $this->redirect('Order',"add&id={$_SESSION['Home']['orderid']}");
        }
        $this->view->display();
    }

    //三级联动
    public function region(){
       //请求小辣椒官网的数据
//        http://www.xiaolajiao.com/region.php?type=3&target=selDistricts_0&parent=123
        $url="http://www.xiaolajiao.com/region.php?type={$_GET['type']}&target={$_GET['target']}&parent={$_GET['parent']}";
        $arr=file_get_contents($url);
        echo $arr;
    }


    //生成订单方法
    public function OrderAdd(){
        $id=$_POST['id']; //购物车id
        $id=trim($id,',');
        $p_id=$_POST['p_id'];//地址id

        //查询数据
        $arr=$this->model->pdo_sel("select f.*,g.kc,g.img,g.name,g.money,u.gname,u.gmoney from sh_flow as f join sh_goods as g on f.g_id = g.id join sh_goods_g as u on f.gg_id = u.id where f.id in ($id)",2);

        $path=$this->model->pdo_sel("select * from sh_path where id = '$p_id'");
        //解决中文乱码问题
        $path['sheng']=urlencode($path['sheng']);
        $path['shi']=urlencode($path['shi']);
        $path['qu']=urlencode($path['qu']);
        $path['txt']=urlencode($path['txt']);
        $path['name']=urlencode($path['name']);

        $list=array();
        $list['m_id']=$_SESSION['Home']['Member']['id'];
        $list['path']=urldecode(json_encode($path)); //转换为json 后 加密
        $list['pay']=$_POST['pay'];
        $list['time']=time();
        $list['ordersn']=date('YmdHis',time()).rand(10,99);
        $money=0;
        foreach($arr as $v){
            $money+=($v['money']+$v['gmoney'])*$v['num'];
        }
        $list['money']=$money;
        //生成 订单数据
        $o_id=$this->model->pdo_insert('sh_order',$list);

        //生成对应的订单商品详情
        foreach($arr as $v){
            $iop=array();
            $iop['g_id']=$v['g_id'];
            $iop['gg_id']=$v['gg_id'];
            $iop['o_id']=$o_id;
            $iop['num']=$v['num'];
            $iop['money']=($v['money']+$v['gmoney'])*$v['num'];
            $this->model->pdo_insert('sh_order_s',$iop);
        }

        //清除购物车数据
        $this->model->pdo_exec("delete from sh_flow where id in ($id)");

        $this->redirect('Order','orderMsg&id='.$o_id);
    }

    //订单详情
    public function orderMsg(){
        $id=$_GET['id']; //订单id
        $arr=$this->model->pdo_sel("select * from sh_order where id  = $id");
        $arr['path']=json_decode($arr['path'],true); //选择的地址信息
        $this->view->assign('arr',$arr);
        $this->view->display();
    }

    //订单支付方法
    public function order(){

        $id=$_GET['id'];//订单id
        $arr=$this->model->pdo_sel("select * from sh_order where id  = $id");

        if($arr['pay']=='支付宝'){
            //实现支付宝支付
            require_once("/Extend/Pay/alipay.config.php");
            require_once("/Extend/Pay/alipay_submit.class.php");
            /**************************请求参数**************************/
            //商户订单号，商户网站订单系统中唯一订单号，必填
            $out_trade_no = $arr['ordersn'];
            //订单名称，必填
            $subject = '商品购买';
            //付款金额，必填
//            $total_fee = $arr['money'];
            $total_fee = 0.01;
            //商品描述，可空
            $body = '商品购买';

//构造要请求的参数数组，无需改动
            $parameter = array(
                "service"       => $alipay_config['service'],
                "partner"       => $alipay_config['partner'],
                "seller_id"  => $alipay_config['seller_id'],
                "payment_type"	=> $alipay_config['payment_type'],
                "notify_url"	=> $alipay_config['notify_url'],
                "return_url"	=> $alipay_config['return_url'],

                "anti_phishing_key"=>$alipay_config['anti_phishing_key'],
                "exter_invoke_ip"=>$alipay_config['exter_invoke_ip'],
                "out_trade_no"	=> $out_trade_no,
                "subject"	=> $subject,
                "total_fee"	=> $total_fee,
                "body"	=> $body,
                "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
                //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.kiX33I&treeId=62&articleId=103740&docType=1
                //如"参数名"=>"参数值"

            );

//建立请求
            $alipaySubmit = new \AlipaySubmit($alipay_config);
            $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
            echo $html_text;
        }
        elseif($arr['pay']=='余额支付'){
            //实现余额支付
        }
    }
    //支付宝同步通知地址
    public function ret(){
        require_once("/Extend/Pay/alipay.config.php");
        require_once("/Extend/Pay/alipay_notify.class.php");

            //商户订单号
            $out_trade_no = $_GET['out_trade_no']; //请求是传递的订单号
            //支付宝交易号
            $trade_no = $_GET['trade_no'];
            //交易状态
            $trade_status = $_GET['trade_status'];
            //金额
            $money2 = $_GET['total_fee'];
            $order=$this->model->pdo_sel("select * from sh_order where ordersn = '$out_trade_no'");
        //判断是否成功
        if(($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') && $money2 == $order['money'] && $order['stat']==1) {
            //修改数据库订单
            $this->model->pdo_upd("sh_order",array('money2'=>$money2,'zfbsn'=>$trade_no,'stat'=>2)," where ordersn = '$out_trade_no'");

            $this->success("支付成功！","Member",'order');
        }else{
            $this->success("支付失败！","Member",'order');
        }
    }
}